package chess.client;

import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.VetoDragException;
import com.allen_sauer.gwt.dnd.client.drop.GridConstrainedDropController;
import com.google.gwt.user.client.ui.AbsolutePanel;

public class ChessBoardDropController extends GridConstrainedDropController {
	public ChessBoard chessBoard;
	
	public ChessBoardDropController(ChessBoard chessBoard, AbsolutePanel dropTarget, int gridX,
			int gridY) {
		super(dropTarget, gridX, gridY);
		
		this.chessBoard = chessBoard;
	}
	
	@Override
	public void onDrop(DragContext context)
	{
		int[] aSquarePos = ChessBoardDragController.getChessSquare(context);

		String PieceColor = chessBoard.activeChessPiece.PieceId.substring(0, 1);
		Integer nPlayer = Constants.PieceColorsIndex.get(PieceColor);

		chessBoard.executeMove(nPlayer
				, new Integer[]{chessBoard.activeChessPiece.row, chessBoard.activeChessPiece.col
									, aSquarePos[0], aSquarePos[1]});
			
		// Clean Up
			chessBoard.activeChessPiece = null;
	}
	
	public void onPreviewDrop(DragContext context) throws VetoDragException {
		int[] aSquarePos = ChessBoardDragController.getChessSquare(context);
		
		String PieceColor = chessBoard.activeChessPiece.PieceId.substring(0, 1);
		Integer nPlayer = Constants.PieceColorsIndex.get(PieceColor);
		
		boolean bLegalMove = Constants.isLegalMove(
				chessBoard.activeChessPiece.PieceId,
				aSquarePos[0]-chessBoard.activeChessPiece.row,
				aSquarePos[1]-chessBoard.activeChessPiece.col,
				chessBoard.activeChessPiece.row,
				chessBoard.activeChessPiece.col,
				chessBoard.chessSquares[aSquarePos[0]][aSquarePos[1]].PieceId
		);

		if (!bLegalMove)	
			throw new VetoDragException();
		
		bLegalMove = chessBoard.isValidMove(nPlayer
				, new Integer[]{
						chessBoard.activeChessPiece.row
						, chessBoard.activeChessPiece.col
						, aSquarePos[0]
						, aSquarePos[1]
				}
		);

		if (!bLegalMove)	
			throw new VetoDragException();
		
		super.onPreviewDrop(context);
	}
}
